//
//  OpenAppCenter.swift
//  App_Common
//
//  Created by 蒋晨成 on 2021/12/24.
//

import Adaptor
import Foundation
import Standard
import StoreKit
import UICore
import UIKit

public enum OpenAppStoreCenter {
    private(set) static weak var viewController: UIViewController?
}

public extension OpenAppStoreCenter {
    static func register(viewController: UIViewController?) {
        self.viewController = viewController
    }
}

extension OpenAppStoreCenter: Actable {
    public static func act(values: [String: Any]) -> Bool {
        guard let type = values["type"] as? Int, let appId = values["appId"] as? String, let presentViewController = viewController else {
            return false
        }
        if type == 1 {
            let storeViewController = SKStoreProductViewController()
            storeViewController.loadProduct(withParameters: [SKStoreProductParameterITunesItemIdentifier: appId]) { _, error in
                guard let error = error else { return }
                logger.error("\(error)")
            }
            presentViewController.present(storeViewController, animated: true, completion: nil)
            return true
        } else if type == 2 {
            if #available(iOS 14, *) {
                SKStoreReviewController.requestReview(in: Adaptor.KeyWindow.scene)
            } else {
                SKStoreReviewController.requestReview()
            }

            return true
        }

        return false
    }

    public static var routePattern: String = "appstore/<int:type>/<string:appId>"
}
